#include <iostream>
#include <cmath>
#include <vector>
#include <fstream>
#include <string>
#include <cstdlib>
#include "Chebyshev.hpp"
using namespace std;

void generateDataFiles(const vector<int>& ns, double c, double d) {
    // 原始函数数据
    ofstream originalFile("original.dat");
    for (double x = c; x <= d; x += 0.01) { // 使用更小的步长以获得平滑曲线
        double y = 1.0 / (1.0 + 25 * pow(x, 2));
        originalFile << x << " " << y << "\n";
    }
    originalFile.close();

    // 不同节点数的插值多项式数据
    for (int n : ns) {
        ofstream interpFile("interp_" + to_string(n) + ".dat");
        double* x = new double[n];
        double* y = new double[n];

        // 生成 Chebyshev 节点
        generateChebyshevNodes(n, x);

        // 将 Chebyshev 节点从 [-1, 1] 映射到 [c, d]
        for (int i = 0; i < n; i++) {
            x[i] = 0.5 * (d - c) * (x[i] + 1) + c;
            y[i] = 1.0 / (1.0 + 25 * pow(x[i], 2)); // 节点处 y 值
        }

        // 为绘制插值多项式生成数据点
        for (double a = c; a <= d; a += 0.01) { // 使用更小的步长以获得平滑曲线
            double interpolatedValue = Chebyshev(x, y, n, a);
            interpFile << a << " " << interpolatedValue << "\n";
        }

        delete[] x;
        delete[] y;
        interpFile.close();
    }
}

int main() {
    // 定义节点数量
    vector<int> ns = {5, 10, 15, 20};
    double c = -1.0, d = 1.0;

    // 生成数据文件
    generateDataFiles(ns, c, d);

    // 调用 gnuplot 绘制图形
    ofstream gp("plot2.gp");
    gp << "set title 'Newton Interpolation'\n";
    gp << "set xlabel 'x'\n";
    gp << "set ylabel 'y'\n";
    gp << "set grid\n";
    gp << "plot 'original.dat' with lines title 'Original Function', \\\n";
    for (int n : ns) {
        gp << "'interp_" << n << ".dat' with lines title 'Interpolation (" << n << " points)', \\\n";
    }
    system("gnuplot -persistent plot2.gp");
    return 0;
}